//
//  ZZNetworkTools.swift
//  sina
//
//  Created by 张鹏 on 16/5/23.
//  Copyright © 2016年 ZP. All rights reserved.
//

import UIKit
//导入命名空间
import AFNetworking
import SVProgressHUD

//声明枚举
//枚举任意类型
enum HTTPMethods: Int {
    case POST
    case GET
}

struct API {
    //线上环境
    static let hostName = "https://api.weibo.com/"
    //测试环境
    //    static let hostName = "https://dev.api.weibo.com/"
    //加载用户token
    static let loadAccessToken = "oauth2/access_token"
    //加载用户信息
    static let loadUserInfo = "2/users/show.json"
    
    //加载首页数据
    static let loadHomedata = "2/statuses/home_timeline.json"
    
    //发布微博
    static let sendStatus = "2/statuses/update.json"
    
}

class ZZNetworkTools: AFHTTPSessionManager {
    //声明单例对象
    static let sharedTools: ZZNetworkTools = {
        //把url前面一样的部分 声明为基础的url地址
        let url = NSURL(string: "https://api.weibo.com/")
        let tools = ZZNetworkTools(baseURL: url)
        
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return tools
    }()
    
    
    //TODO:   //封装 get & post 请求方法
 
    func request(method: HTTPMethods,urlString: String, parameters: AnyObject?,finished: (responseObject: AnyObject?, error: NSError?) -> () ) {
        
        //定义闭包参数 将相同的闭包当做参数传递
        let success = { (task: NSURLSessionDataTask, result: AnyObject?) -> () in
            //执行请求成功的回调
            finished(responseObject: result, error: nil)
        }
        
        let failure = { (task: NSURLSessionDataTask?, error: NSError) -> () in
            //执行失败的回调
            finished(responseObject: nil, error: error)
        }
        
        if method == .GET {
            
            GET(urlString, parameters: parameters, progress: nil, success: success, failure: failure)
            //            // "_" 表示忽略
            //            GET(urlString, parameters: parameters, progress: nil, success: { (_, result) in
            //                //执行请求成功的回调
            //                finished(responseObject: result, error: nil)
            //                }, failure: { (_, error) in
            //                    //执行失败的回调
            //                    finished(responseObject: nil, error: error)
            //            })
        } else {
            
            POST(urlString, parameters: parameters, progress: nil, success: success, failure: failure)
            //            POST(urlString, parameters: parameters, progress: nil, success: { (_, result) in
            //                //执行请求成功的回调
            //                finished(responseObject: result, error: nil)
            //                }, failure: { (_, error) in
            //                    //执行失败的回调
            //                    finished(responseObject: nil, error: error)
            //            })
        }
    }
    
}

//登录信息

extension ZZNetworkTools {

    func loadAccessToken (code : String , finished : (responseObject : AnyObject? , error : NSError?) -> () ) {
        //获取网络请求
        let urlString = "oauth2/access_token"
        let parameters = ["client_id":client_id, "client_secret":client_secret, "grant_type":"authorization_code", "code":code, "redirect_uri":redirect_uri]
        //发送网络请求
        request(.POST, urlString: urlString, parameters: parameters, finished: finished)

    }
    
    
    func loadUserInfo(result : [String : AnyObject] , finished : (responseObject : AnyObject? , error : NSError?) -> () ) {

        //字典中不可以添加nil,  token uid 是可选项, 所以要强制解包
        let token = result["access_token" ]!
        let uid = result["uid"]!
        
        let parameters = ["access_token":token, "uid":uid]
    
        request(.GET, urlString: API.loadUserInfo, parameters: parameters, finished: finished)
    }

}

//首页相关
extension ZZNetworkTools {
    
    func loadHomePageData(finished: (responseObject: AnyObject?, error: NSError?) -> ()) {
        guard let token = ZZUserAccountViewModel.sharedAccountViewModel.userAccount?.access_token else {
            return
        }
        let parameters = ["access_token": token]
//        if  since_id > 0 {
//            parameters["since_id"] = "\(since_id)"
//        }
//        if max_id > 0 {
//            parameters["max_id"] = "\(max_id - 1)"
//        }
        request(.GET, urlString: API.loadHomedata, parameters: parameters, finished: finished)
    }
    
}


//发送微博
extension ZZNetworkTools {
    func sendStatus(status: String,finished: (responseObject: AnyObject?, error: NSError?) -> ()) {
        guard let token = ZZUserAccountViewModel.sharedAccountViewModel.userAccount?.access_token else {
            return
        }
        
        let parameters = ["access_token": token,"status":status]
        request(.POST, urlString: API.sendStatus, parameters: parameters, finished: finished)
    }
}


